package xml_test;

import java.io.IOException;

import junit.framework.Assert;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.junit.Test;

import xml.Dom4JFileReader;
import xml.Dom4JXmlWriter;
import xml.DomHolder;

public class Dom4JXmlWriterTest
{
	@Test
	public void writeXml() throws IOException, DocumentException
	{
		String path = "src-test-resources/testwriter.xml";
		Dom4JXmlWriter writer = new Dom4JXmlWriter();
		Document doc = DomHolder.getInstance().getDom();
		Assert.assertNotNull(doc);
		
		Element root = doc.getRootElement();
		Element vokabel = root.addElement("vokabel");
		vokabel.addAttribute("id", ""+1234);
		
		
		Element german = vokabel.addElement("german");
		german.addText("gehen");
		
		Element english = vokabel.addElement("english");
		english.addText( "to go") ;

		Element lvlGerman = vokabel.addElement("lvlGerman");
		lvlGerman.addAttribute("lvl", ""+3);
		
		Element lvlEnglish = vokabel.addElement("lvlEnglish");
		lvlEnglish.addAttribute("lvl", ""+2);
		
		writer.writeXml(path);
		
		// read created Xml
		
		Dom4JFileReader reader = new Dom4JFileReader();
		doc = reader.readDocument(path);
		
		root = doc.getRootElement();
		Assert.assertEquals("vokabeln", root.getName());
		
		vokabel = root.element("vokabel");
		Assert.assertEquals("vokabel", vokabel.getName());
		Assert.assertEquals("1234", vokabel.attributeValue("id"));
		
		lvlGerman = vokabel.element("lvlGerman");
		Assert.assertEquals("lvlGerman", lvlGerman.getName());
		Assert.assertEquals("3", lvlGerman.attributeValue("lvl"));
		
		german = vokabel.element("german");
		Assert.assertEquals("gehen", german.getTextTrim());
		
		english = vokabel.element("english");
		Assert.assertEquals("to go", english.getText());
		
		lvlEnglish = vokabel.element("lvlEnglish");
		Assert.assertEquals("2", lvlEnglish.attributeValue("lvl"));
	}
}
